#ifndef __BUFFER_HPP__

#define __BUFFER_HPP__

#include <cassert>
#include <vector>
#include <algorithm>

#define BUFFER_DEFAULT_SIZE (1 * 1024 * 1024)    // 默认大小
#define BUFFER_INCREMENT_SIZE (1 * 1024 * 1024)  // 阈值大小,大于该值时每次扩容的大小
#define BUFFER_THRESHOLD_SIZE (10 * 1024 * 1024) // 阈值大小,小于该值扩容时翻倍

namespace Log
{
    class Buffer
    {
    private:
        size_t _read_idx;  // 读位置
        size_t _write_idx; // 写位置
        std::vector<char> _v;   // 缓冲区
    public:
        Buffer() : _read_idx(0), _write_idx(0), _v(BUFFER_DEFAULT_SIZE) {}
        void push(const char *date, size_t len) // 写入数据
        {
            ensureEnoughSpace(len);
            std::copy(date, date+len, &_v[_write_idx]);
            _write_idx += len;
        }
        void pop(size_t len) // 删除数据
        {
            _read_idx += len;
            assert(_read_idx <= _write_idx);
        }
        const char *begin() // 返回可读数据的起始地址
        {
            return &_v[_read_idx];
        }
        size_t readAbleSize() // 返回数据可读大小
        {
            return _write_idx - _read_idx;
        }
        size_t writeAbleSize() // 返回可写大小
        {
            return _v.size() - _write_idx;
        }
        void swap(Buffer &buffer) // 交换缓冲区
        {
            _v.swap(buffer._v);
            std::swap(_write_idx, buffer._write_idx);
            std::swap(_read_idx, buffer._read_idx);
        }
        bool empty() // 判空
        {
            return _write_idx == _read_idx;
        }
        void reset() // 重置
        {
            _write_idx = 0;
            _read_idx = 0;
        }

    private:
        void ensureEnoughSpace(size_t len) // 保证足够可写大小空间
        {
            if (len < writeAbleSize())
                return;
            size_t newSize = 0;
            if (_v.size() < BUFFER_THRESHOLD_SIZE)
                newSize = _v.size() * 2 + len;
            else
                newSize = _v.size() + BUFFER_INCREMENT_SIZE + len;
            _v.resize(newSize);
        }
    };
}

#endif // !__BUFFER_HPP__